
package com.xiaoma.myaudience.biz.app;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.XmlResourceParser;
import android.graphics.Bitmap;
import android.text.TextUtils;
import cn.jpush.android.api.JPushInterface;
import cn.sharesdk.framework.AbstractWeibo;

import com.baidu.location.LocationClient;
import com.xiaoma.myaudience.R;
import com.xiaoma.myaudience.biz.model.ActivitySelectInfoModel;
import com.xiaoma.myaudience.biz.model.UserAccount;
import com.xiaoma.myaudience.biz.util.Constant;
import com.xiaoma.myaudience.util.FileUtils;
import com.xiaoma.myaudience.util.Logger;
import com.xiaoma.myaudience.util.app.BaseApplication;

public class AudienceApplication extends BaseApplication {
    public static final String TAG = "AudienceApplication";

    public static final String ACTION_LOGIN = "com.netease.video.ACTION_LOGIN";

    // 图片缓存
    private static final HashMap<String, SoftReference<Bitmap>> sBitmapCache = new HashMap<String, SoftReference<Bitmap>>();

    public static List<Map<String, Object>> sProvince ;
    public static List<Map<String, Object>> sCity ;
    
    /** 登陆账号 未登录为 null */
    private String mApplicationAccount;

    private String mApplicationPassword;
    
    public LocationClient mLocationClient = null;
	public String mLocation;

    @Override
    public void onCreate() {
    	mLocationClient = new LocationClient(this);
    	
        super.onCreate();
        
      //初始化ShareSDK
      	AbstractWeibo.initSDK(this);
      	//极光推送注册服务
      	JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
      	
        // TODO 刷新登录账号,考虑放在一个独立线程执行
        refreshLoginAccount();

        // TODO 每次启动清空临时图片
        FileUtils.delete(Constant.FILE_TMP_IMG);
        
        sProvince =  getDataFromXml(R.xml.provinces, "Province", "ID", "ProvinceName");
        sCity =  getDataFromXml(R.xml.cities, "City", "PID", "CityName");
    }    

    @Override
    public void onLowMemory() {
        super.onLowMemory();

        try {
			synchronized (sBitmapCache) {
			    Iterator<Entry<String, SoftReference<Bitmap>>> iterator = sBitmapCache.entrySet()
			            .iterator();
			    while (iterator.hasNext()) {
			        Entry<String, SoftReference<Bitmap>> entry = iterator.next();
			        SoftReference<Bitmap> sr = entry.getValue();
			        if (sr == null || sr.get() == null) {
			            sBitmapCache.remove(entry.getKey());
			        }
			    }
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

    }

    @Override
    public void onTerminate() {
        super.onTerminate();
//        getContentResolver().unregisterContentObserver(mLoginObserver);
    }

    /**
     * 刷新用户登陆账号
     */
    public void refreshLoginAccount() {
        final boolean lastLogin = isLogin();
        final String lastAccount = mApplicationAccount;

        mApplicationAccount = null;
        mApplicationPassword = null;
        String[] projects = new String[] {
                UserAccount.USERNAME, UserAccount.PASSWORD
        };
        final ContentResolver resolver = getContentResolver();

//        Cursor cursor = resolver.query(UserAccountDbHelper.getUri(), projects,
//                new WhereStringBuilder().append(UserAccount.ISLOGIN).toString(), new String[] {
//                    "1"
//                }, null);

//        if (cursor != null) {
//            try {
//                if (cursor.moveToFirst()) {
//                    mApplicationAccount = cursor.getString(0);
//                    mApplicationPassword = cursor.getString(1);
//                }
//            } finally {
//                cursor.close();
//            }
//        }

        final boolean isLogin = isLogin();

        if ((!lastLogin && !isLogin)
                || (lastLogin && isLogin && mApplicationAccount.equals(lastAccount))) {
            return;
        }

        Logger.d(TAG, isLogin ? mApplicationAccount + " login " : " logout ");
        sendBroadcast(new Intent(ACTION_LOGIN));
    }

    /**
     * 判断是否登陆
     * 
     * @return
     */
    public boolean isLogin() {
        return !TextUtils.isEmpty(mApplicationAccount);
    }

    /**
     * 获取登陆账号
     * 
     * @return
     */
    public String getUserAccount() {
        return mApplicationAccount;
    }

    public String getUserPassword() {
        return mApplicationPassword;
    }

    /**
     * 设置定时
     * 
     * @param intent
     * @param interval
     */
    public void addAlarm(Intent intent, int interval) {
        PendingIntent alarmIntent = PendingIntent.getService(this, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarms.cancel(alarmIntent);

        if (interval == -1) {
            // 默认5分钟
            interval = 5 * 60 * 1000;
            // interval = 5 * 1000;
        }

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.add(Calendar.MILLISECOND, interval);

        // TODO ... 如果程序异常退出了，定时器还会发送,但是不会执行service
        alarms.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), interval,
                alarmIntent);
        // alarms.set(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime() +
        // interval, alarmIntent);
    }

    /**
     * 删除定时
     * 
     * @param intent
     */
    public void deleteAlarm(Intent intent) {
        PendingIntent alarmIntent = PendingIntent.getService(this, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarms.cancel(alarmIntent);
    }

    /**
     * 增加图片缓存
     * 
     * @param key
     * @param bitmap
     */
    public void addBitmapCache(String key, Bitmap bitmap) {
        synchronized (sBitmapCache) {
            if (bitmap == null) {
                sBitmapCache.remove(key);
            } else {
                sBitmapCache.put(key, new SoftReference<Bitmap>(bitmap));
            }
        }
    }

    /**
     * 删除图片缓存
     * 
     * @param key
     */
    public void deleteBitmapCache(String key) {
        synchronized (sBitmapCache) {
            sBitmapCache.remove(key);
        }
    }

    /**
     * 从缓存获取图片
     * 
     * @param key
     */
    public Bitmap getBitmapCache(String key) {
        SoftReference<Bitmap> r = sBitmapCache.get(key);
        return r == null ? null : r.get();
    }
    
    private List<Map<String, Object>> getDataFromXml(int xml, String...param) {
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		XmlResourceParser parser = getResources().getXml(xml);
		try {
			while (parser.getEventType() != XmlResourceParser.END_DOCUMENT) {
				if (parser.getEventType() == XmlResourceParser.START_TAG) {
					String tagName = parser.getName();
					if (tagName.equals(param[0])) {
						Map<String, Object> map = new HashMap<String, Object>();
						String id = parser.getAttributeValue(null, param[1]);
						map.put(param[1], id);
						String name = parser.getAttributeValue(null, param[2]);
						map.put(ActivitySelectInfoModel.PARAM_CLASSNAME, name);
						list.add(map);
					}
				}
				parser.next();
			}
		} catch (Exception e) {
			
		}
		
		return list;
	}
}
